package com.zego.wawaji.ui.Fragment;

import android.Manifest;
import android.annotation.TargetApi;
import android.app.AppOpsManager;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Binder;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.zego.wawaji.R;
import com.zego.wawaji.ui.dialog.PickerDialogUtil;
import com.zego.wawaji.ui.dialog.SimpleTipDialog;

import java.lang.reflect.Method;

/**
 * 应用内Fragment基类
 */
public class BaseFragment extends Fragment {

    public BaseFragment() {
        super();
    }

    private LayoutInflater inflater;
    private ViewGroup container;
    private View contentView;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        this.inflater = inflater;
        this.container = container;
        //checkOverLaysPermission(); // 悬浮窗权限检测
        return super.onCreateView(inflater, container, savedInstanceState);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    /**
     * 为标题栏预留出状态栏空间
     */
    private void setImmerseLayout() {
        try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
//                View view = contentView.findViewById(R.id.base_title_bg);
//                if (view != null)
//                    view.setPadding(0, App.statusBarHeight, 0, 0);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 设置内容组件
     */
    public View setContentView(int resourcesId) {
        contentView = inflater.inflate(resourcesId, container, false);
        setImmerseLayout();
        return contentView;
    }

    /**
     * 获取内容组件
     */
    public View getContentView() {
        return this.contentView;
    }

    /**
     * 查找组件
     */
    public View findViewById(int id) {
        return contentView.findViewById(id);
    }

    /**
     * 设置标题
     */
    public void setTitle(String txt) {
        TextView textView = (TextView) contentView.findViewById(R.id.base_title_title);
        textView.setVisibility(View.VISIBLE);
        textView.setText(txt);
    }

    /**
     * 设置标题右侧文字
     */
    public void setTitleRight(String txt, View.OnClickListener listener) {
        TextView textView = (TextView) contentView.findViewById(R.id.base_title_right);
        textView.setVisibility(View.VISIBLE);
        textView.setOnClickListener(listener);
        textView.setText(txt);
    }

    /**
     * 设置标题左侧图片
     */
    public ImageView setTitleLeftImg(int res, View.OnClickListener listener) {
        ImageView iv = (ImageView) contentView.findViewById(R.id.base_left_img);
        ImageView back = (ImageView) contentView.findViewById(R.id.base_back);
        iv.setBackgroundResource(res);
        iv.setVisibility(View.VISIBLE);
        back.setVisibility(View.GONE);
        iv.setOnClickListener(listener);
        return iv;
    }

    /**
     * 设置标题左侧文字
     */
    public void setTitleLeft(String txt, View.OnClickListener listener){
        TextView textView = (TextView) contentView.findViewById(R.id.title_left_text);
        textView.setVisibility(View.VISIBLE);
        textView.setOnClickListener(listener);
        textView.setText(txt);
    }

    /**
     * 设置标题左侧文字隐藏
     */
    public void setTitleLeftGone(){
        TextView textView = (TextView) contentView.findViewById(R.id.title_left_text);
        textView.setVisibility(View.GONE);
    }

    /**
     * 设置标题右侧图片
     */
    public ImageView setTitleRightImg(int res, View.OnClickListener listener) {
        ImageView iv = (ImageView) contentView.findViewById(R.id.base_title_right_img);
        iv.setBackgroundResource(res);
        iv.setVisibility(View.VISIBLE);
        iv.setOnClickListener(listener);
        return iv;
    }


    // =================== 权限检测 =================================

    /**
     * 是否是特殊机型： 魅族、小米
     */
    private boolean isSpecial() {
        return "Xiaomi".equals(Build.MANUFACTURER)
                || "Meizu".equals(Build.MANUFACTURER);
    }

    /**
     * 手动检测悬浮窗权限
     */
    protected boolean checkOverLaysPermission() {
        // 小米魅族手机，去主动开启授权
        if (isSpecial()) {
            if (isFloatWindowOpAllowed()) return true;
            permissionAuth();
            return false;
        }

        // API22以下
        if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.LOLLIPOP_MR1) return true;

        if (!Settings.canDrawOverlays(getActivity())) {
            permissionAuth();  // 未开启时，手动授权
            return false;
        }
        return true;
    }

    // 手动悬浮窗授权
    private void permissionAuth() {
        PickerDialogUtil.showSimpleAlertDialog(getActivity(), new SimpleTipDialog.ConfirmListener() {
            @Override
            public void onCancel() {
            }

            @Override
            public void onSubmit() {
                if (isSpecial()) {
                    openSetting();
                } else {
                    Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:" + getActivity().getPackageName()));
                    startActivity(intent);
                }
            }
        }, "请开启悬浮窗权限，未开启可能造成程序部分功能使用异常！", R.color.text_black, "");
    }

    /**
     * 权限检测
     */
    private boolean checkSelfPermission(String permission, int requestCode) {
        if (ContextCompat.checkSelfPermission(getActivity(),
                permission)
                != PackageManager.PERMISSION_GRANTED) {

            ActivityCompat.requestPermissions(getActivity(),
                    new String[]{permission},
                    requestCode);
            return false;
        }

        if (Manifest.permission.CAMERA.equals(permission)) {
        }
        return true;
    }

    /**
     * 权限动态申请结果
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
        }
    }

    /**
     * 魅族手机： 打开权限设置界面 ， 上面手动开启授权界面无效果？？？？
     */
    public void openSetting() {
        try {
            Intent localIntent = new Intent(
                    "miui.intent.action.APP_PERM_EDITOR");
            localIntent.setClassName("com.miui.securitycenter",
                    "com.miui.permcenter.permissions.AppPermissionsEditorActivity");
            localIntent.putExtra("extra_pkgname", getActivity().getPackageName());
            startActivityForResult(localIntent, 11);

        } catch (ActivityNotFoundException localActivityNotFoundException) {
            Intent intent1 = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
            Uri uri = Uri.fromParts("package", getActivity().getPackageName(), null);
            intent1.setData(uri);
            startActivityForResult(intent1, 11);
        }
    }

    /**
     * 判断悬浮窗权限
     */
    @TargetApi(Build.VERSION_CODES.KITKAT)
    public boolean isFloatWindowOpAllowed() {
        final int version = Build.VERSION.SDK_INT;
        if (version >= 19) {
            return checkOp(24);  // AppOpsManager.OP_SYSTEM_ALERT_WINDOW
        } else {
            return (getActivity().getApplicationInfo().flags & 1 << 27) == 1 << 27;
        }
    }

    @TargetApi(Build.VERSION_CODES.KITKAT)
    public boolean checkOp(int op) {
        final int version = Build.VERSION.SDK_INT;

        if (version >= 19) {
            AppOpsManager manager = (AppOpsManager) getActivity().getSystemService(Context.APP_OPS_SERVICE);
            try {

                Class<?> spClazz = Class.forName(manager.getClass().getName());
                Method method = manager.getClass().getDeclaredMethod("checkOp", int.class, int.class, String.class);
                int property = (Integer) method.invoke(manager, op,
                        Binder.getCallingUid(), getActivity().getPackageName());
                return AppOpsManager.MODE_ALLOWED == property;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return false;
    }
}
